//
//  OSSImageUploader.m
//  OSSImsgeUpload
//
//  Created by cysu on 5/31/16.
//  Copyright © 2016 cysu. All rights reserved.
//

#import "OSSImageUploader.h"
#import "AliyunOSSiOS.h"
#import "OSSService.h"
#import "En_ResponseStatus.h"
//#import <AliyunOSSiOS/OSSService.h>

@implementation OSSImageUploader

static NSString *const BucketName = @"dahuaxiyou-web";

static NSString *const AliYunHost = @"https://oss-cn-beijing.aliyuncs.com";

static NSString * kTempFolder = @"permissions/v1/oss";


+ (void)asyncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{
    
    [[DataManager manager]getUserOssAuthorityWithBlock:^(NSDictionary *posts, En_ResponseStatus *status, NSError *error) {
        NSString * ss = [NSString stringWithFormat:@"%@",status.data1];
        if ([ss isEqualToString:@"1"]) {
            [self uploadImages:@[image] isAsync:YES  ststoken:[posts valueForKey:@"SecurityToken"] accessKeyId:[posts valueForKey:@"AccessKeyId"] secretKeyId:[posts valueForKey:@"AccessKeySecret"] complete:complete];
        }
    }];
}

+ (void)syncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{
    [[DataManager manager]getUserOssAuthorityWithBlock:^(NSDictionary *posts, En_ResponseStatus *status, NSError *error) {
   
        NSString * ss = [NSString stringWithFormat:@"%@",status.code];
   
        if ([ss isEqualToString:@"1"]) {
            [self uploadImages:@[image] isAsync:NO ststoken:[posts valueForKey:@"SecurityToken"] accessKeyId:[posts valueForKey:@"AccessKeyId"] secretKeyId:[posts valueForKey:@"AccessKeySecret"] complete:complete];
        }
    }];
}

+ (void)asyncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
    [[DataManager manager]getUserOssAuthorityWithBlock:^(NSDictionary *posts, En_ResponseStatus *status, NSError *error) {
    NSString * ss = [NSString stringWithFormat:@"%@",status.data1];
    if ([ss isEqualToString:@"1"]) {
            [self uploadImages:images isAsync:YES ststoken:[posts valueForKey:@"SecurityToken"] accessKeyId:[posts valueForKey:@"AccessKeyId"] secretKeyId:[posts valueForKey:@"AccessKeySecret"] complete:complete];
        }
    }];
}

+ (void)syncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{
    [[DataManager manager]getUserOssAuthorityWithBlock:^(NSDictionary *posts, En_ResponseStatus *status, NSError *error) {
    NSString * ss = [NSString stringWithFormat:@"%@",status.data1];
    if ([ss isEqualToString:@"1"]) {
            
            [self uploadImages:images isAsync:NO ststoken:[posts valueForKey:@"SecurityToken"] accessKeyId:[posts valueForKey:@"AccessKeyId"] secretKeyId:[posts valueForKey:@"AccessKeySecret"] complete:complete];
        }
    }];
}

+ (void)uploadImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync ststoken:(NSString *)ststoken accessKeyId:(NSString *)accessKeyId secretKeyId:(NSString *)secretKeyId complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete{
    
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:secretKeyId securityToken:ststoken];

    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    
    // 网络请求遇到异常失败后的重试次数
    conf.maxRetryCount = 3;
    
    // 网络请求的超时时间
    conf.timeoutIntervalForRequest =30;
    
    // 允许资源传输的最长时间
    conf.timeoutIntervalForResource =24 * 60 * 60;
    
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = images.count;
    
    NSMutableArray *callBackNames = [NSMutableArray array];
    int i = 0;
    for (UIImage *image in images) {
        if (image) {
            NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                //任务执行
                OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                put.bucketName = BucketName;
                NSString *imageName = [kTempFolder stringByAppendingPathComponent:[[NSUUID UUID].UUIDString stringByAppendingString:@".jpg"]];
                put.objectKey = imageName;
                [callBackNames addObject:imageName];
                NSData *data = UIImageJPEGRepresentation(image, 0.3);
                put.uploadingData = data;
                put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
                    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
                };
                OSSTask * putTask = [client putObject:put];
                [putTask waitUntilFinished]; // 阻塞直到上传完成
                if (!putTask.error) {
                    NSLog(@"upload object success!");
                } else {
                    NSLog(@"upload object failed, error: %@" , putTask.error);
                }
                if (isAsync) {
                    if (image == images.lastObject) {
                        NSLog(@"upload object finished!");
                        if (complete) {
                            complete([NSArray arrayWithArray:callBackNames] ,UploadImageSuccess);
                        }
                    }
                }
            }];
            if (queue.operations.count != 0) {
                [operation addDependency:queue.operations.lastObject];
            }
            [queue addOperation:operation];
        }
        i++;
    }
    if (!isAsync) {
        [queue waitUntilAllOperationsAreFinished];
        NSLog(@"haha");
        if (complete) {
            if (complete) {
                complete([NSArray arrayWithArray:callBackNames], UploadImageSuccess);
            }
        }
    }
}


@end
